<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getFinanceStatisticsAPI } from '../services/finance'
import type { FinanceStatistics } from '@/types/finance'

const statistics = ref<FinanceStatistics | null>(null)
const isLoading = ref(true)
const dateRange = ref({
  startDate: new Date(new Date().getFullYear(), 0, 2).toISOString().split('T')[0],
  endDate: new Date().toISOString().split('T')[0],
})
const chartsDataPie = ref({
  series: [
    {
      data: [
        {
          name: '收入',
          value: 1500,
        },
        {
          name: '支出',
          value: 300,
        },
      ],
    },
  ],
})

// 获取统计数据
const fetchStatistics = async () => {
  try {
    isLoading.value = true
    const res = await getFinanceStatisticsAPI(dateRange.value)
    statistics.value = res.data
    chartsDataPie.value = {
      series: [
        {
          data: [
            {
              name: '收入',
              value: res.data.totalIncome,
            },
            {
              name: '支出',
              value: res.data.totalExpense,
            },
          ],
        },
      ],
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    uni.showToast({ title: '获取数据失败', icon: 'error' })
  } finally {
    isLoading.value = false
  }
}

// 切换日期范围
const changeDateRange = (range: 'month' | 'quarter' | 'year') => {
  const now = new Date()
  let startDate
  const endDate = now.toISOString().split('T')[0]

  switch (range) {
    case 'month':
      startDate = new Date(now.getFullYear(), now.getMonth(), 2).toISOString().split('T')[0]
      break
    case 'quarter':
      {
        const quarterStartMonth = Math.floor(now.getMonth() / 3) * 3
        startDate = new Date(now.getFullYear(), quarterStartMonth, 2).toISOString().split('T')[0]
      }
      break
    case 'year':
      startDate = new Date(now.getFullYear(), 0, 2).toISOString().split('T')[0]
      break
  }

  dateRange.value = { startDate, endDate }
  fetchStatistics()
}

// 自定义日期范围选择
const customDateRange = () => {
  // 这里可以实现自定义日期范围选择器
  // 为了简化，暂时不实现完整的日期范围选择功能
  uni.showToast({ title: '自定义日期范围功能待实现', icon: 'none' })
}

onMounted(() => {
  fetchStatistics()
})
</script>

<template>
  <view class="page-container">
    <view class="statistics-content">
      <!-- 日期范围选择 -->
      <view class="date-range-selector">
        <view class="date-range-options">
          <view class="date-range-option" @click="changeDateRange('month')">
            <text>本月</text>
          </view>
          <view class="date-range-option" @click="changeDateRange('quarter')">
            <text>本季度</text>
          </view>
          <view class="date-range-option" @click="changeDateRange('year')">
            <text>本年</text>
          </view>
          <view class="date-range-option custom" @click="customDateRange">
            <text>自定义</text>
          </view>
        </view>
        <view class="date-display">
          <text>{{ dateRange.startDate }} 至 {{ dateRange.endDate }}</text>
        </view>
      </view>

      <!-- 财务概览 -->
      <view class="financial-overview">
        <view class="overview-item">
          <text class="overview-label">总收入</text>
          <text class="overview-value income">¥{{ statistics?.totalIncome || 0 }}</text>
        </view>
        <view class="overview-item">
          <text class="overview-label">总支出</text>
          <text class="overview-value expense">¥{{ statistics?.totalExpense || 0 }}</text>
        </view>
        <view class="overview-item">
          <text class="overview-label">净利润</text>
          <text class="overview-value profit">¥{{ statistics?.netProfit || 0 }}</text>
        </view>
      </view>

      <!-- 趋势图表 -->
      <view class="chart-container">
        <view class="chart-title">收支趋势</view>
        <view class="chart-content">
          <!-- 实际项目中这里会是一个图表组件 -->
          <view v-if="isLoading" class="chart-loading">
            <text>加载中...</text>
          </view>
          <view v-else-if="statistics" class="chart-placeholder">
            <qiun-data-charts type="pie" :chartData="chartsDataPie" />
          </view>
        </view>
      </view>

      <!-- 分类统计 -->
      <view class="category-statistics">
        <view class="category-title">收入分类</view>
        <view class="category-list">
          <!-- 收入分类列表 -->
          <view v-if="statistics" class="category-items">
            <view
              class="category-item"
              v-for="record in statistics.incomeByCategory"
              :key="record.id"
            >
              <text class="category-name">{{ record.category }}</text>
              <text class="category-amount">¥{{ record.amount }}</text>
            </view>
          </view>
          <view v-else-if="!isLoading" class="no-data">
            <text>暂无收入数据</text>
          </view>
        </view>

        <view class="category-title">支出分类</view>
        <view class="category-list">
          <!-- 支出分类列表 -->
          <view v-if="statistics" class="category-items">
            <view
              class="category-item"
              v-for="record in statistics.expenseByCategory"
              :key="record.id"
            >
              <text class="category-name">{{ record.category }}</text>
              <text class="category-amount">¥{{ record.amount }}</text>
            </view>
          </view>
          <view v-else-if="!isLoading" class="no-data">
            <text>暂无支出数据</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.page-container {
  height: 100vh;
  background-color: #f5f7fa;
  padding: 20rpx;
  box-sizing: border-box;
}

.statistics-content {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
}

.date-range-selector {
  margin-bottom: 30rpx;
  .date-range-options {
    display: flex;
    margin-bottom: 15rpx;
    .date-range-option {
      flex: 1;
      text-align: center;
      padding: 15rpx;
      background-color: #f5f7fa;
      margin: 0 5rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #666;
    }
    .date-range-option.custom {
      border: 1rpx dashed #999;
    }
  }
  .date-display {
    text-align: center;
    font-size: 26rpx;
    color: #999;
  }
}

.financial-overview {
  display: flex;
  margin-bottom: 30rpx;
  .overview-item {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    background-color: #f5f7fa;
    margin: 0 10rpx;
    border-radius: 10rpx;
    .overview-label {
      display: block;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    .overview-value {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
    }
    .overview-value.income {
      color: #409eff;
    }
    .overview-value.expense {
      color: #f56c6c;
    }
    .overview-value.profit {
      color: #67c23a;
    }
  }
}

.chart-container {
  margin-bottom: 30rpx;
  .chart-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  .chart-content {
    height: 400rpx;
    background-color: #f5f7fa;
    border-radius: 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .chart-loading,
  .chart-placeholder {
    color: #999;
    font-size: 28rpx;
  }
}

.category-statistics {
  .category-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  .category-list {
    margin-bottom: 30rpx;
    .category-items {
      .category-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background-color: #f5f7fa;
        margin-bottom: 10rpx;
        border-radius: 8rpx;
        .category-name {
          font-size: 28rpx;
          color: #333;
        }
        .category-amount {
          font-size: 28rpx;
          font-weight: bold;
          color: #666;
        }
      }
    }
    .no-data {
      padding: 60rpx 0;
      text-align: center;
      color: #999;
      font-size: 28rpx;
    }
  }
}

/* 响应式适配 */
@media screen and (max-width: 320px) {
  .statistics-content {
    padding: 15rpx;
  }
  .financial-overview {
    flex-direction: column;
    .overview-item {
      margin: 5rpx 0;
    }
  }
  .chart-content {
    height: 300rpx;
  }
}
</style>
